package com.thinkingcoder.tcsharding.datasource;

import java.util.LinkedHashMap;
import java.util.Map;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.thinkingcoder.tcsharding.engine.ShardingContext;
import com.thinkingcoder.tcsharding.engine.ShardingResult;
import com.thinkingcoder.tcsharding.property.ShardingProperties;

/**
 * sharding dataSource.
 */
public class ShardingDataSource extends AbstractRoutingDataSource {

    /**
     * 使用 ShardingProperties 创建多数据源
     * 
     * @param properties 配置信息
     */
    public ShardingDataSource(ShardingProperties properties) {
        Map<Object, Object> dataSourceMap = new LinkedHashMap<>();
        properties.getDataSources().forEach((k, v) -> {
            try {
                // 创建 Druid 数据源
                dataSourceMap.put(k, DruidDataSourceFactory.createDataSource(v));
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });
        // 将创建好的数据源，设置到 AbstractRoutingDataSource
        setTargetDataSources(dataSourceMap);
        // 设置默认数据源（用作兜底操作）
        setDefaultTargetDataSource(dataSourceMap.values().iterator().next());
    }

    @Override
    protected Object determineCurrentLookupKey() {
        // 通过ThreadLocal机制，动态获取SQL语句执行时，需要的数据源
        ShardingResult result = ShardingContext.get();
        Object targetDataSourceName = result == null ? null : result.getTargetDataSourceName();
        System.out.println(" ===> determineCurrentLookupKey: " + targetDataSourceName);
        return targetDataSourceName;
    }

}
